package com.luoying.itew.fragment;

import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.luoying.itew.R;
import com.luoying.itew.bean.CollectBean;
import com.luoying.itew.bean.HourChartRBean;
import com.luoying.itew.common.AntaiApplication;
import com.luoying.itew.http.HttpRequestUtils;
import com.luoying.itew.http.HttpResponseCallBack;
import com.luoying.itew.util.BarChartManage;
import com.luoying.itew.util.LogUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/8/7.
 * time 2018-5-10
 * author zm
 */
public class ChartsHourFragment extends BaseFragment {
    private static final String TAG = "ChartsHourFragment";
    @BindView(R.id.tv_charthour_start_time)
    TextView tvCharthourStartTime;
    @BindView(R.id.rl_charthour_start_time)
    RelativeLayout rlCharthourStartTime;
    @BindView(R.id.sp_charthour)
    Spinner spCharthour;
    @BindView(R.id.rl_charthour_end_time)
    RelativeLayout rlCharthourEndTime;
    @BindView(R.id.rl_charthour_search)
    RelativeLayout rlCharthourSearch;
    @BindView(R.id.lr_chart_search)
    LinearLayout lrChartSearch;
    Unbinder unbinder;
    @BindView(R.id.sp_type)
    Spinner spType;
    @BindView(R.id.barchart_hour)
    BarChart barchartHour;
    private TimePickerView startPickView;
    private String startTime;
    private ArrayList<String> collectName;
    private ArrayList<Integer> collectId;
    private ArrayAdapter<String> arr_adapter;
    private int currentCollectId;
    private int displacementType = 1;   //时位移图表类型
    private ArrayList<Float> xValues = new ArrayList<>();
    private ArrayList<Float> yValues = new ArrayList<>();
    private List<String> categoryDatas;
    private BarChartManage barChartManage;
    private List<Double> series;
    private int namePosition;

    @Override
    protected int getLayoutResId() {
        return R.layout.charts_hour_fragment;
    }

    @Override
    protected void init() {
        super.init();
        setThings();
        sendCollectRequest();
    }

    private void setThings() {


        spCharthour.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                currentCollectId = collectId.get(position);
                namePosition = position;
                LogUtils.d(TAG, collectId + ",position == " + position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                displacementType = position + 1;
                //LogUtils.d(TAG, ",position == " + position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        tvCharthourStartTime.setText(df.format(day));
        startTime = df.format(day);

        barChartManage = new BarChartManage(barchartHour);
        barchartHour.setScaleXEnabled(true);
        barchartHour.setScaleYEnabled(false);
        barchartHour.getDescription().setEnabled(false);   //设置描述
    }

    private void sendCollectRequest() {
        HttpRequestUtils.getInstance().collectDetail(AntaiApplication.cuurMonitorId, new HttpResponseCallBack<Map>() {
            @Override
            public void onFail(String message) {
                if (loadDialog != null) {
                    loadDialog.dismiss();
                }
                LogUtils.d(TAG, "onFail == " + message);
            }

            @Override
            public void onSuccess(Map bean) {
                String response = new Gson().toJson(bean);
                LogUtils.d(TAG, response);
                CollectBean collectBean = new Gson().fromJson(response, CollectBean.class);
                setSpinner(collectBean);
            }

            @Override
            public void onError(String message) {
                if (loadDialog != null) {
                    loadDialog.dismiss();
                }
                LogUtils.d(TAG, "onError == " + message);
            }
        });
    }

    /**
     * 设置选择监测点Spinner
     *
     * @param collectBean
     */
    private void setSpinner(CollectBean collectBean) {
        List<CollectBean.DataBean> data = collectBean.getData();
        collectName = new ArrayList<String>();
        collectId = new ArrayList<Integer>();
        for (int i = 0; i < data.size(); i++) {
            collectName.add(data.get(i).getCollectorName());
            collectId.add(data.get(i).getCollectorId());
        }
        //设置默认值
        currentCollectId = collectId.get(0);
        //适配器
        arr_adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, collectName);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spCharthour.setAdapter(arr_adapter);
        sendChartRequest();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.rl_charthour_start_time, R.id.lr_chart_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_charthour_start_time:
                showStartDateDialog();
                break;
            case R.id.lr_chart_search:
                loadDialog.show();
                sendChartRequest();
                break;
        }
    }

    /**
     * 图表查询
     */
    private void sendChartRequest() {
        LogUtils.d(TAG, "monitorPointId == " + AntaiApplication.cuurMonitorId + ",displacementType == " + displacementType + ",yearAndMonth == " + startTime + ",monitorId == " + currentCollectId);
        HttpRequestUtils.getInstance().hourChart(AntaiApplication.cuurMonitorId, displacementType, startTime, currentCollectId, new HttpResponseCallBack<Map>() {
            @Override
            public void onFail(String message) {
                LogUtils.d(TAG, "Update onFail == " + message);
                loadDialog.dismiss();
            }

            @Override
            public void onSuccess(Map data) {
                String s = new GsonBuilder().disableHtmlEscaping().create().toJson(data);
                LogUtils.d(TAG, "Update onSuccess == " + s);
                HourChartRBean hourChartRBean = new Gson().fromJson(s, HourChartRBean.class);
                setData(hourChartRBean);
                loadDialog.dismiss();
            }

            @Override
            public void onError(String message) {
                loadDialog.dismiss();
                LogUtils.d(TAG, "Update onError == " + message);
            }
        });
    }

    private void setData(HourChartRBean hourChartRBean) {
        if (categoryDatas != null && categoryDatas.size() != 0) {
            categoryDatas.clear();
        }
        categoryDatas = hourChartRBean.getCategoryDatas();
        xValues.clear();
        yValues.clear();
        for (int i = 0; i < categoryDatas.size(); i++) {
            xValues.add((float) i);
        }

        series = hourChartRBean.getSeries();
        for (int i = 0; i < series.size(); i++) {
            yValues.add(Float.valueOf(series.get(i) + ""));
        }
        barchartHour.invalidate();
        barchartHour.clear();
        XAxis xAxis = barchartHour.getXAxis();

        if (displacementType == 2){
            Matrix m = new Matrix();
            m.postScale(1.8f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
            barchartHour.getViewPortHandler().refresh(m, barchartHour, false);//将图表动画显示之前进行缩放
            xAxis.setLabelRotationAngle(30f);  //设置旋转偏移量
        }else {
            Matrix m = new Matrix();
            m.postScale(1f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
            barchartHour.getViewPortHandler().refresh(m, barchartHour, false);//将图表动画显示之前进行缩放
            xAxis.setLabelRotationAngle(0f);  //设置旋转偏移量
        }
        barChartManage.showBarChart(xValues, yValues, collectName.get(namePosition), R.color.blue);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if (value<categoryDatas.size()){
                    return categoryDatas.get((int) value);
                }else {
                    return "";
                }
            }
        });


    }

    private void showStartDateDialog() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);
        //正确设置方式 原因：注意事项有说明
        // mYear = .get(Calendar.YEAR); // 获取当前年份
        int mYear = endDate.get(Calendar.YEAR);
        int month = endDate.get(Calendar.DAY_OF_MONTH);
        int date = endDate.get(Calendar.DATE);
        startDate.set(2018, 0, 1);
//        endDate.set(2020,11,31);
        selectedDate.set(mYear, month, date);
        startPickView = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM", Locale.getDefault());
                String tempBirthday = df.format(date);
                LogUtils.d(TAG, "startTime Select == " + tempBirthday);
                startTime = tempBirthday;
                tvCharthourStartTime.setText(tempBirthday);
            }
        })
                .setType(new boolean[]{true, true, false, false, false, false})// 默认年月日是否全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTextColorOut(Color.BLACK)
                .setTextColorCenter(0xFF333333)
                .setTitleSize(20)//标题文字大小
                .setTitleText("日期选择")//标题文字
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(0xFF888888)//确定按钮文字颜色
                .setCancelColor(0xFF888888)//取消按钮文字颜色
                .setTitleBgColor(0xFFeeeeee)//标题背景颜色 Night mode
                .setBgColor(0xFFffffff)//滚轮背景颜色 Night mode
                .isCyclic(false)//是否循环滚动
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        startPickView.show();
    }
}
